<script>
  function getRandomInt(min, max) {
    min = Math.ceil(min) // 确保最小值为正整数
    max = Math.floor(max) // 确保最大值为非负整数
    return Math.floor(Math.random() * (max - min + 1)) + min // 返回[min, max]范围内的随机整数
  }
  // 获取盐 { randPosition, randStringList }
  function getSalt(str) {
    let fix = 'abcdefghijklmnopqrstuvwxyz1234567890'
    let len = parseInt(str.length * 0.5)
    let temp = []
    for (let i = 0; i < len; i++) {
      let r = getRandomInt(0, len)
      temp.push(r)
    }
    let randPosition = Array.from(new Set(temp))
    let randStringList = []
    for (let i = 0; i < randPosition.length; i++) {
      let rIndex = getRandomInt(0, fix.length - 1)
      randStringList.push(fix[rIndex])
    }
    return {
      randPosition: randPosition.sort((a, b) => {
        return a - b
      }),
      randStringList
    }
  }
  // { randPosition_new 新的盐位置, value }
  function addSalt(slat, str) {
    const { randPosition, randStringList } = slat
    let strList = str.split('')
    for (let i = randPosition.length - 1; i >= 0; i--) {
      let idx = randPosition[i]
      strList.splice(idx, 0, randStringList[i])
    }
    // 加盐后，盐位置会发生变化，比如原来的是[1,3,4,5] -> [1,4,6,8], 变化规律 [+0, +1, +2, +3]
    // 因此如果要得到新的盐位置
    let randPosition_new = []
    for (let i = 0; i <= randPosition.length - 1; i++) {
      randPosition_new.push(randPosition[i] + i)
    }
    return {
      randPosition_new,
      value: strList.join('')
    }
  }
  function removeSalt(randPosition_new, str) {
    let strList = str.split('')
    for (let i = randPosition_new.length - 1; i >= 0; i--) {
      let idx = randPosition_new[i]
      strList.splice(idx, 1)
    }
    return strList.join('')
  }
  let str = '0123456789'
  let salt = getSalt(str)
  let { value: saltAfterStr, randPosition_new } = addSalt(salt, str)
  let removeSaltAfterStr = removeSalt(randPosition_new, saltAfterStr)
  console.info('原字符串', str)
  console.info('盐-旧位置', salt.randPosition)
  console.info('盐-新位置', randPosition_new)
  console.info('加盐后', saltAfterStr)
  console.info('删盐后', removeSaltAfterStr)
</script>
